package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xrit.sunnyday.dao.UserMapper;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.pojo.User;
import com.xrit.sunnyday.service.UserService;
import com.xrit.sunnyday.common.PageResult;
import com.xrit.sunnyday.common.QueryPageBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //判断是否有条件
        if(!(StringUtils.isEmpty(queryPageBean.getQueryString()))){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        //开启分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //调用查询方法
        List<User> userList = userMapper.findPage(queryPageBean.getQueryString());
        //放到pageinfo中
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        //将处理结果返回
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public List<Role> findAllRole() {
        return userMapper.findAllRole();
    }

    @Override
    public void add(User user) {
        //调用添加到用户表方法
        userMapper.add(user);
        //调用添加到中间表的方法
        List<Integer> roleIds = user.getRoleIds();
        System.out.println(roleIds);
        for (Integer roleId : roleIds) {
            userMapper.addUserRole(user.getId(),roleId);
        }

    }

    @Override
    public void deleteById(Integer id) {
        //调用dao层根据id查询t_user_role
        int count = userMapper.findUserRoelById(id);
        //判断 >0代表有关系
        if(count>0){
            //先解除该用户和角色的关系
            userMapper.deleleUserRoleById(id);
        }
        //调用根据id删除用户的方法
        userMapper.deleteById(id);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public List<Integer> findUserRoleById(Integer id) {
        return userMapper.findUserRoleById(id);
    }

    @Override
    public void update(User user) {
        //调用修改user的方法
        userMapper.update(user);
        //先解除该用户和角色的旧关系
        userMapper.deleleUserRoleById(user.getId());
        //在添加该用户和角色新的关系
        List<Integer> roleIds = user.getRoleIds();
        for (Integer roleId : roleIds) {
            //调用添加到中间表的方法
            userMapper.addUserRole(user.getId(),roleId);
        }
    }

    @Override
    public User findByUserName(String username) {
        return userMapper.findByUsername(username);
    }
}
